/**
 * PHOSIDE: PHosphorylation Site IDentification Engine.
 * Copyright 2009 Digital Biology Lab, University of Missouri.
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 3 of the License, or (at your option) any later
 * version. <p/> This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more
 * details.
 */

package phoside.ui;

import java.io.File;
import java.io.IOException;

import java.util.ArrayList;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import phoside.PhosideInit;
import phoside.PhosphoProteins;
import phoside.PhosphoProteins.PhosphoType;
import phoside.PhosphoProteinsImpl;

import phoside.data.util.PhosphoDataUtil;

import phoside.io.ProteinsReader;
import phoside.io.fasta.PhosphoReaderFromFastaWithSitesInSequence;
import phoside.io.xml.PhosideXmlProteinsReader;
import phoside.io.xml.PhosphoProteinFieldValueFormatter;

import phoside.ui.task.ProteinsReadTask;
import phoside.ui.task.TaskUtil;

import phoside.util.FileExtensionsFilter;
import phoside.util.FilePathParser;
import phoside.util.StaticFinalValues;

/**
 *
 * @author gjj
 */
public class FileStatisticsDialog extends javax.swing.JDialog {

    /** Creates new form PhosideTrainDialog */
    public FileStatisticsDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        trainFileButtonActionPerformed(null);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        javax.swing.JPanel trainPanel = new javax.swing.JPanel();
        javax.swing.JPanel trainFilePanel = new javax.swing.JPanel();
        trainFileTextField = new javax.swing.JTextField();
        javax.swing.JButton trainFileButton = new javax.swing.JButton();
        javax.swing.JPanel inputfileoptionPanel = new javax.swing.JPanel();
        javax.swing.JPanel viewPanel = new javax.swing.JPanel();
        javax.swing.JScrollPane viewScrollPane = new javax.swing.JScrollPane();
        javax.swing.JPanel OKPanel = new javax.swing.JPanel();
        javax.swing.JButton closelBtn = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("File Statistics");
        getContentPane().setLayout(new java.awt.GridBagLayout());

        trainPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Sequence file"));
        trainPanel.setMinimumSize(new java.awt.Dimension(400, 63));
        trainPanel.setPreferredSize(new java.awt.Dimension(500, 63));
        trainPanel.setLayout(new java.awt.GridBagLayout());

        trainFilePanel.setLayout(new java.awt.GridBagLayout());

        trainFileTextField.setToolTipText("Please select a FASTA training file");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        trainFilePanel.add(trainFileTextField, gridBagConstraints);

        trainFileButton.setText("Open");
        trainFileButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                trainFileButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        trainFilePanel.add(trainFileButton, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.weightx = 1.0;
        trainPanel.add(trainFilePanel, gridBagConstraints);

        inputfileoptionPanel.setLayout(new java.awt.GridBagLayout());
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        trainPanel.add(inputfileoptionPanel, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(trainPanel, gridBagConstraints);

        viewPanel.setLayout(new java.awt.GridBagLayout());

        viewScrollPane.setViewportView(viewTable);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        viewPanel.add(viewScrollPane, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(viewPanel, gridBagConstraints);

        closelBtn.setText("Close");
        closelBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closelBtnActionPerformed(evt);
            }
        });
        OKPanel.add(closelBtn);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(OKPanel, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void trainFileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_trainFileButtonActionPerformed
        JFileChooser fc = new JFileChooser(PhosideInit.defaultPath);
        
        ArrayList<String> exts = new ArrayList<String>(1);
        String fasta = "fasta";
        exts.add(fasta);
        fc.addChoosableFileFilter(new FileExtensionsFilter(exts,"Fasta file (.fasta)"));

        exts = new ArrayList<String>(1);
        String xml = "xml";
        exts.add(xml);
        fc.addChoosableFileFilter(new FileExtensionsFilter(exts,"Xml file (.xml)"));

        fc.setDialogTitle("Select a file...");
        int returnVal = fc.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            PhosideInit.defaultPath = file.getParent();

            String filePath = PhosideInit.defaultPath + File.separator + file.getName();
            trainFileTextField.setText(filePath);
            
            String ext = FilePathParser.getExt(filePath);

            ProteinsReader reader;
            PhosphoProteins proteins = new PhosphoProteinsImpl();
            if (ext.equalsIgnoreCase("fasta")) {
                try {
                    reader = new PhosphoReaderFromFastaWithSitesInSequence(filePath, proteins, StaticFinalValues.DEFAULTHEADERRULE);
                } catch (IOException e) {
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(this, "Error: failed to open the file.");
                    return;
                }
            } else if (ext.equalsIgnoreCase("xml")) {
                reader = new PhosideXmlProteinsReader(filePath, proteins, new PhosphoProteinFieldValueFormatter());
            } else {
                JOptionPane.showMessageDialog(this, "Error: only .fasta and .xml are supported");
                return;
            }

            ProteinsReadTask task = new ProteinsReadTask(reader);
            TaskUtil.execute(task);
            if (!task.success()) {
                JOptionPane.showMessageDialog(this, "Failed to read the file");
                return;
            }

            viewTable.setProteins(proteins);
        }
    }//GEN-LAST:event_trainFileButtonActionPerformed

    private void closelBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closelBtnActionPerformed
        setVisible(false);
        this.dispose();
}//GEN-LAST:event_closelBtnActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField trainFileTextField;
    // End of variables declaration//GEN-END:variables
    
    private ViewPhosphoTable viewTable = new ViewPhosphoTable(null);
}

class ViewPhosphoTable extends JTable {

    private final String headerParam = "Attribute";
    private final String headerValue = "Value";

    public ViewPhosphoTable(PhosphoProteins proteins) {
        this.setEnabled(false);
        setProteins(proteins);
    }

    public void setProteins(PhosphoProteins proteins) {
        if (proteins==null) {
            setModel(new DefaultTableModel());
            return;
        }

        PhosphoType[] types = PhosphoType.values();
        Object[][] data = new Object[2*types.length+2][];
        
        data[0] = new Object[]{"No. of Proteins", proteins.getProteinsAccessions().size()};
        data[1] = new Object[]{"No. of Phosphoproteins", PhosphoDataUtil.countPhosphoProteins(proteins, null)};

        int i = 2;
        for (PhosphoType type : types) {
            data[i++] = new Object[]{"No. of "+type.fullName()+"s",PhosphoDataUtil.countResidue(proteins, type.aatype())};
            data[i++] = new Object[]{"No. of Phospho"+type.fullName()+"s", PhosphoDataUtil.countPhosphosites(proteins, type)};
        }

        setModel(new DefaultTableModel(data, new String[]{headerParam, headerValue}));
    }
}